package com.ynny.practice5_2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Component("CouserManage")
public class CouserManageImpl implements CouserManage{
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void updateCouser(String couresName) {
        String sql = "update cousers set"+couresName+"="+couresName+"-1";
        int i = jdbcTemplate.update(sql);
        if(i<= 0){
            System.out.println("更新失败");
        }

    }

    @Override
    public void queryCouser() {
        String sql = "select * from couser";
        RowMapper<Couser> rowMapper ;
        rowMapper = new BeanPropertyRowMapper<Couser>(Couser.class);
        Couser couser = jdbcTemplate.queryForObject(sql,rowMapper);
        System.out.println(couser);

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false,isolation = Isolation.DEFAULT)
    public void slectCouser(String number, String couresName) {
        updateCouser(couresName);
        queryCouser();
        jdbcTemplate.execute("create table if not exists optional_couser("+"number varchar(20),score double)");
        String sql = "insert into couser(number,couresName,score) value (?,?,?)";
        jdbcTemplate.update(sql,number,couresName,0.0);
        System.out.println("选课记录");
        sql = "select * from couser where number=?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,number);
        for (Map<String, Object> map : list) {
            System.out.println(map);
        }
    }
}
